﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

public class LoginPanel : BasePanel
{

	public Button executeLoginBtn;

	public Button closeBtn;

	public InputField phoneTextInputField;

	public InputField passwordInputTextField;


	private LoginRequest _loginRequest;
	
	void Start () {
		
		//组件初始化
		_loginRequest = this.gameObject.GetComponent<LoginRequest>();
		
		
		//按钮点击事件函数绑定
		closeBtn.onClick.AddListener(delegate { CloseButtonClicked(); });
		executeLoginBtn.onClick.AddListener(delegate { LoginButtonClicked(); });
		
		
	}

	// Update is called once per frame
	void Update () {
		
	}
	
	public override void OnEnter()
	{
		//动画初始大小
		this.transform.localScale=Vector3.zero;
		
		if(!this.gameObject.activeSelf){
			this.gameObject.SetActive(true);
		}

		this.transform.DOScale(new Vector3(1, 1, 1), 0.5f);


	}

	public override void OnPause()
	{
		
	}

	public override void OnResume()
	{
		
	}

	public override void OnExit()
	{
		this.transform.DOScale(Vector3.zero, 0.5f).OnComplete(delegate { this.gameObject.SetActive(false); });

	}

	// Use this for initialization
	
	private void CloseButtonClicked()
	{
		UnityFacade.Instance.UiManager.PopPanel();
	}


	private void LoginButtonClicked()
	{
		//todo 发起登录请求
		_loginRequest.SendRequest(phoneTextInputField.text,passwordInputTextField.text);
		
	}

	public void handleResponse(JsonData respJson)
	{
		string status = respJson["state"].ToString();
		if (status.Equals("success"))
		{
			int userId =(int) respJson["data"]["userId"];
			string userName = respJson["data"]["userName"].ToString();
			string password =respJson["data"]["password"].ToString();
			string phone =respJson["data"]["phone"].ToString();
			string nick =respJson["data"]["nick"].ToString();
//			respJson["data"]["createTime"];
			string avatar =respJson["data"]["avatar"].ToString();
			User activeUser = new User();
			activeUser.UserId = userId;
			activeUser.Password = password;
			activeUser.UserName = userName;
			activeUser.Nick = nick;
			activeUser.Phone = phone;
			activeUser.Avatar = avatar;


			UnityFacade.Instance.ApplicationManager.ActiveUser = activeUser;
			UnityFacade.Instance.UiManager.PopPanel();//弹出登录Panel
			UnityFacade.Instance.UiManager.PushPanel(PanelType.ChatListPanel);// todo 聊天

		}
		else
		{
			//登录失败的情况处理
			Debug.Log(respJson["msg"].ToString());
			MsgPanel msgPanel =(MsgPanel) UnityFacade.Instance.UiManager.PushPanel(PanelType.Msg);
			msgPanel.SyncShow("fail",respJson["msg"].ToString());
		}
	}
}
